//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "framework\fn_executeObjectAction.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;
private ["_object","_caller","_act_id","_arguments","_actions","_action","_action_type","_action_id","_parameters","_func_name","_func","_params"];
DEFAULT_PARAM(_object,0,objNull);
if (typename _object != typename objNull) exitWith {ERROR_1("Parameter is not an object",_this);};
if (isnull _object) exitWith {ERROR_1("Parameter is not set",_this);};
DEFAULT_PARAM(_caller,1,objNull);
DEFAULT_PARAM(_act_id,2,-1);
DEFAULT_PARAM(_arguments,3,[]);

if (count _arguments <= 0) exitWith {ERROR_1("Argument is not set",_this);};

_action_id = GETVAL(_arguments, TMF_EXECUTE_ACTION_PARAM_ACTID, -1);
_function = GETVAL(_arguments, TMF_EXECUTE_ACTION_PARAM_FUNC, "");

_action_type = "";
_params = [];
_params set [TMF_EXECUTE_ACTION_OBJECT, _object];
_params set [TMF_EXECUTE_ACTION_CALLER, _caller];
_params set [TMF_EXECUTE_ACTION_ID, _act_id];
_params set [TMF_EXECUTE_ACTION_ARGS, _arguments];
_parameters = [];
_func = "";

if (_action_id >= 0 && _function == "") then {
	_actions = [_object] call FFUNC(GetActions);
	_action = [_actions,_action_id] call FFUNC(actionGet);
	if (count _action <= 0) exitWith {ERROR_2("Action is not set",_action_id,_actions);};
	TRACE_2("Executing Action",_action_id,_action);
	_action_type = [_action] call FFUNC(actionGetType);
	_parameters = [_action] call FFUNC(actionGetParams);
	_params set [TMF_EXECUTE_ACTION_ACTION, _action];
} else {
	if (_function != "") then {
		_action_type = _function;
	};
};

if (_action_type == "") exitWith {ERROR("Action Type is not set");};

if (GVAR(SERVER)) then {
	_func_name = format["%1%2",QUOTE(FFUNC(serverExecute)),_action_type];
	if (!isnil _func_name) then {
		call compile format["_func = %1",_func_name];
		TRACE_1("Execute Object Action",ARR_4(_func_name,_object, typeof _object, _parameters));
		_params call _func;
	} else {
		DEBUG_1("Action doesn't exist",ARR_4(_func_name,_action_id,_action_type,_parameters));
	};
};
if (GVAR(CLIENT)) then {
	_func_name = format["%1%2",QUOTE(FFUNC(clientExecute)),_action_type];
	if (!isnil _func_name) then {
		call compile format["_func = %1",_func_name];
		TRACE_1("Execute Object Action",ARR_4(_func_name,_object, typeof _object, _parameters));
		_params call _func;
	} else {
		DEBUG_1("Action doesn't exist",ARR_4(_func_name,_action_id,_action_type,_parameters));
	};
};
TRACE("End");
TMFPROFILERSTOP;
